Page Index
27 A seata分布式事务
JL 于 2023-07-26 16:10:22 +08:00 修改了此页面
此文件含有模棱两可的 Unicode 字符

此文件含有可能会与其他字符混淆的 Unicode 字符。 如果您是想特意这样的,可以安全地忽略该警告。 使用 Escape 按钮显示他们。

  • 该文档是在joolunV2.8.7版本上编写,使用nacos1.3.2+seata1.3.0+spring-cloud-alibaba2.2.3.RELEASE组合,后期版本升级了不一定适用,以官方文档为准

系统中暂未用到分布式事务,默认情况下无需启动

详情

  • Seata 是一款开源的分布式事务解决方案,致力于提供高性能和简单易用的分布式事务服务。Seata 将为用户提供了 AT、TCC、SAGA 和 XA 事务模式,为用户打造一站式的分布式解决方案。官方地址
  • 实例说明

上图所示,当请求A服务时
1. A服务做增删改操作完
1. 使用Feign调用B服务
1. B服务做增删改操作完
1. 合并1、3两步操作
2. 返回处理结果

异常分析
1. 步骤1发生异常,spring 事务会自动回滚
1. 步骤2发生异常,spring 事务会自动回滚
1. 步骤3发生异常,3会自动回滚,根据返回的自定义异常1会自动回滚
1. 步骤4发生异常,spring事务会自动回滚 ,***但是3的操作不会回滚***

分布式事务的作用就是当A模块开启事务时,如果步骤4发生异常,3的操作也要回滚
registry {
  # file 、nacos 、eureka、redis、zk、consul、etcd3、sofa
  type = "nacos"
  nacos {
    application = "seata-server"
    serverAddr = "127.0.0.1:8848"
    group = "SEATA_GROUP"
    namespace = ""
    cluster = "default"
    username = "nacos"
    password = "nacos"
  }
}

config {
  # file、nacos 、apollo、zk、consul、etcd3
  type = "nacos"
  nacos {
    serverAddr = "127.0.0.1:8848"
    namespace = ""
    group = "SEATA_GROUP"
    username = "nacos"
    password = "nacos"
  }
}

  • 使用步骤

    1、nacos中配置seata相关信息,我们已整理成sql文件seata-server\sql\nacos-config.sql,直接导入base_config库后重启nacos即可

    2、在两个服务的pom中引入事务管理依赖

    <!--分布式事务-->
    <dependency>
        <groupId>com.joolun</groupId>
        <artifactId>base-common-transaction</artifactId>
    </dependency>
    

    3、nacos中分别在两个服务的配置文件中添加seata相关配置信息

    #seata分布式配置
    seata:
      enabled: true
      #此处配置自定义的seata事务分组名称,和service.vgroupMapping.xxxx-seata-service-group对应
      tx-service-group: xxxx-seata-service-group
      config:
        type: nacos
        nacos:
          application: seata-server
          server-addr: 127.0.0.1:8848
          group: "SEATA_GROUP"
          namespace: ""
          cluster: "default"
          username: "nacos"
          password: "nacos"
      registry:
        type: nacos
        nacos:
          application: seata-server
          server-addr: 127.0.0.1:8848
          group: "SEATA_GROUP"
          namespace: ""
          cluster: "default"
          username: "nacos"
          password: "nacos"
    

    4、nacos中分别给两个服务添加vgroupMapping配置文件,注意要和上面的分组名称对应vgroupMapping.xxxx-seata-service-group = "default"

    5、在A服务需要开启事务的方法上加上@GlobalTransactional注解

  • 启动seata-server服务端seata-server/bin

    window系统启动双击seata-server.bat
    
    linux系统启动运行seata-server.sh,命令如下
    
    `nohup sh ./seata-server/bin/seata-server.sh >joolun-seata.out &`
    
  • 再重启各服务